//
//  RegisterPhoneNumber.m
//  XJMTechnician
//
//  Created by Mr.hu on 2017/10/18.
//  Copyright © 2017年 Mr.hu. All rights reserved.
//

#import "RegisterIdentityCard.h"
#import "QiniuSDK.h"

@interface RegisterIdentityCard ()<UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *InputIdentityInforText;
@property (weak, nonatomic) IBOutlet UIButton *IdentityCompleteBtn;

@property (strong, nonatomic) UIImagePickerController * pickController;
@property (nonatomic,strong)  NSData * headdata;
@property (nonatomic,strong)  UIImage * headImage; //
@property (nonatomic,strong)  UIImage * Second_headImage; //

@property (weak, nonatomic) IBOutlet UIButton *Front_IdentImage;
@property (weak, nonatomic) IBOutlet UIButton *Reverse_IdentImage;

@property(nonatomic,copy)finishBlock myBlock;

@end

@implementation RegisterIdentityCard

-(instancetype)initWithBlock:(finishBlock)block
{
    if (self = [super init]) {
        self.myBlock = block;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addLeftBtn:[UIImage imageNamed:@"fanhui"] Action:@selector(backToPrevious)];
    self.title = @"身份验证";
    self.InputIdentityInforText.delegate =self;
    self.IdentityCompleteBtn.layer.cornerRadius = 22;
    
    self.pickController = [[UIImagePickerController alloc]init];
    self.pickController.allowsEditing = YES;
    self.pickController.delegate = self;
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jkr_tapGestureAction:)];
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGestureRecognizer];
}

- (void)jkr_tapGestureAction:(UITapGestureRecognizer *)tapGusture{
    [self.view endEditing:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.InputIdentityInforText resignFirstResponder];
    
    return NO;
}

- (IBAction)CompleteIdentityMeth:(id)sender {
    
    if (self.Identity_Reverse == nil || self.Identity_Font == nil || self.identityInforma == nil) {
        [XJToolClass tipAnimationWith:@"请补全信息"];
    }else{
        self.myBlock(self.InputIdentityInforText.text, self.Identity_Reverse, self.Identity_Font);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (IBAction)FrontViewImageMeth:(UIButton *)sender {
    
    self.Front_IdentImage.tag = 100;
    
        UIAlertController * aler = [UIAlertController alertControllerWithTitle:@"选取照片" message:nil preferredStyle:0];
        UIAlertAction * actionone = [UIAlertAction actionWithTitle:@"照片库" style:0 handler:^(UIAlertAction *action) {
            
            self.pickController.sourceType = UIImagePickerControllerCameraCaptureModePhoto;
            [self presentViewController:self.pickController animated:YES completion:^{
                
            }];
        }];
        
        UIAlertAction * actiontwo = [UIAlertAction actionWithTitle:@"拍照" style:0 handler:^(UIAlertAction *action) {
            
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                
                UIAlertController * a = [UIAlertController alertControllerWithTitle:@"提示" message:@"该设备不存在摄像功能或摄像已损坏！" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [a addAction:act];
                [self presentViewController:a animated:YES completion:nil];
                
            }else
            {
                self.pickController.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:self.pickController animated:YES completion:nil];
            }
            
        }];
        UIAlertAction * actionthree = [UIAlertAction actionWithTitle:@"胶卷" style:0 handler:^(UIAlertAction *action) {
            self.pickController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            [self presentViewController:self.pickController animated:YES completion:nil];
        }];
        UIAlertAction * actionfour = [UIAlertAction actionWithTitle:@"取消" style:1 handler:^(UIAlertAction *action) {
        }];
        [aler addAction:actionone];
        [aler addAction:actiontwo];
        [aler addAction:actionthree];
        [aler addAction:actionfour];
        [self presentViewController:aler animated:YES completion:nil];
    
    
}

- (IBAction)ConverPhotoMethImage:(UIButton *)sender {
    
    self.Front_IdentImage.tag = 200;
    UIAlertController * aler = [UIAlertController alertControllerWithTitle:@"选取照片" message:nil preferredStyle:0];
    UIAlertAction * actionone = [UIAlertAction actionWithTitle:@"照片库" style:0 handler:^(UIAlertAction *action) {
        
        self.pickController.sourceType = UIImagePickerControllerCameraCaptureModePhoto;
        [self presentViewController:self.pickController animated:YES completion:^{
            
        }];
    }];
    
    UIAlertAction * actiontwo = [UIAlertAction actionWithTitle:@"拍照" style:0 handler:^(UIAlertAction *action) {
        
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIAlertController * a = [UIAlertController alertControllerWithTitle:@"提示" message:@"该设备不存在摄像功能或摄像已损坏！" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [a addAction:act];
            [self presentViewController:a animated:YES completion:nil];
            
        }else
        {
            self.pickController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:self.pickController animated:YES completion:nil];
        }
        
    }];
    UIAlertAction * actionthree = [UIAlertAction actionWithTitle:@"胶卷" style:0 handler:^(UIAlertAction *action) {
        self.pickController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:self.pickController animated:YES completion:nil];
    }];
    UIAlertAction * actionfour = [UIAlertAction actionWithTitle:@"取消" style:1 handler:^(UIAlertAction *action) {
    }];
    [aler addAction:actionone];
    [aler addAction:actiontwo];
    [aler addAction:actionthree];
    [aler addAction:actionfour];
    [self presentViewController:aler animated:YES completion:nil];
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    if (self.Front_IdentImage.tag == 100) {
        
        [self dismissViewControllerAnimated:YES completion:^{
               [self.Front_IdentImage  setBackgroundImage:nil forState:UIControlStateNormal];
            [self.Front_IdentImage setImage:info[UIImagePickerControllerEditedImage] forState:UIControlStateNormal];
            self.Front_IdentImage.imageView.contentMode = UIViewContentModeScaleAspectFit;
        }];
        
        self.headImage = info[UIImagePickerControllerEditedImage];
        
        [LoadingView showCircleView: self.view];
        [XJHttpClass ReceiveQiniuTokenFinishblock:^(id response, NSString *errStr) {
            if (errStr) {
                [XJToolClass tipAnimationWith:errStr];
            }else{
                
                NSDictionary * datadict = response[@"data"];
                NSString * qiniu_token = datadict[@"upToken"];
                
                self.headdata = UIImagePNGRepresentation(self.headImage);
                
                QNUploadManager *upManager = [[QNUploadManager alloc] init];
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                [formatter setDateFormat:@"YYYYMMddHHmmss"];
                NSDate *datenow = [NSDate date];
                
                NSString *currentTimeString = [NSString stringWithFormat:@"%@.jpg",[formatter stringFromDate:datenow]];
                
                QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:@"text/plain" progressHandler:nil params:@{ @"x:foo":@"fooval" } checkCrc:YES cancellationSignal:nil];
                
                [LoadingView hide];
                [upManager putData:self.headdata key:currentTimeString token:qiniu_token
                          complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                             
                              self.Identity_Font = [NSString stringWithFormat:@"%@/%@",kQiniuBaseUrl ,resp[@"key"]];
                              
                          } option:opt];
            }
        }];
        
    }else if (self.Front_IdentImage.tag ==200){
        
        [self dismissViewControllerAnimated:YES completion:^{
            [self.Reverse_IdentImage setBackgroundImage:nil forState:UIControlStateNormal];
            [self.Reverse_IdentImage setImage:info[UIImagePickerControllerEditedImage] forState:UIControlStateNormal];
            self.Reverse_IdentImage.imageView.contentMode = UIViewContentModeScaleAspectFit;
        }];
        self.Second_headImage = info[UIImagePickerControllerEditedImage];
        
        [LoadingView showCircleView:self.view];
        [XJHttpClass ReceiveQiniuTokenFinishblock:^(id response, NSString *errStr) {
        
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
        }else{
            
            NSDictionary * datadict = response[@"data"];
            NSString * qiniu_token = datadict[@"upToken"];
            
            self.headdata = UIImagePNGRepresentation(self.Second_headImage);
            
            QNUploadManager *upManager = [[QNUploadManager alloc] init];
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"YYYYMMddHHmmss"];
            NSDate *datenow = [NSDate date];
            
            NSString *currentTimeString = [NSString stringWithFormat:@"%@.jpg",[formatter stringFromDate:datenow]];
                                             
            QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:@"text/plain" progressHandler:nil params:@{ @"x:foo":@"fooval" } checkCrc:YES cancellationSignal:nil];
            
            [upManager putData:self.headdata key:currentTimeString token:qiniu_token
                      complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                          
                          [LoadingView hide];
                          self.Identity_Reverse = [NSString stringWithFormat:@"%@/%@",kQiniuBaseUrl,resp[@"key"]];
                          
                          self.identityInforma = self.InputIdentityInforText.text;
                          
                      } option:opt];
           }
    }];
    }
//     NSData * headdata = UIImagePNGRepresentation(self.headImage);
//    [self.MineSettingTable reloadData];
}


@end
